package server;
import java.net.Socket;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import shared.WifiObject;

/**
 * @author Donovan
 * 
 * Object created to communicate with a connected user.
 * Each user has their own thread (IncomingPort) so that the server can
 * communicate with several at the same time.
 *
 */
public class ClientUser {

	private static final int SLEEP_TIME = 200;
	private Socket socket;
	private boolean connected;
	private Incomingport incomingPort;
		
	public ClientUser(Socket newSocket) {
		socket = newSocket;
		connected = true;
		incomingPort = new Incomingport();
		incomingPort.start();
	}

	public boolean isConnected() {
		return connected;
	}
	
	public void purge() {
		try{
			connected = false;
			socket.close();
		} catch(IOException e){
			System.out.println("Could not purge " + socket + ".");
		}
	}
	
	public String toString(){
		return new String(socket.toString());
	}
	
	private class Incomingport extends Thread {
		private ObjectInputStream in;
		@SuppressWarnings("unused")
		private ObjectOutputStream out;
		
		public void run() {
			try {
				in = new ObjectInputStream(socket.getInputStream());
				out = new ObjectOutputStream(socket.getOutputStream());
			} catch(IOException e) {
				System.out.println("Clould not get input stream from " + toString());
				return;
			} 
						
			while(true){
				try {
					Object obj = null;
					while((obj = in.readObject()) != null){
						if(obj instanceof String){						
							//Does nothing right now
						} else if(obj instanceof WifiObject) {
							WifiObject wo = (WifiObject)obj;
							if(wo.isProfile()){
								String query = "INSERT INTO location (SSID, BSSID, macAddress," +
										"signalStrength, linkSpeed, netId, otherNetworks, homeLocation) VALUES (" +
										"'" + wo.getSSID() + "', '" + wo.getBSSID() + "', '" + wo.getMacAddress() +
										"', " + wo.getSignalStrength() + ", " + wo.getLinkSpeed() + ", " +
										wo.getNetId() + ", '" + wo.getOtherNetworks() + "', '" + wo.getHomeLocation() + "')";
								Database.getInstance().queryUpdate(query);
								System.out.println("Received a Profile WifiObject");
							} else {
								System.out.println("Received a non-Profile WifiObject");
								//Grab information from database and do 
								//whatever with it right about here
							}
						}
					}
				} catch (ClassNotFoundException e) {
					System.out.println(e);
				} catch (IOException e1) {
					purge();
					System.out.println(toString() + " has disconnected");
					return;
				} 
			
				try {				
					Thread.sleep(SLEEP_TIME);
				} catch(Exception e){
					System.out.println(toString() + " has input interrupted.");
				}
			}
		}
	}
}
